package com.akuhome.resource.service.entity;

import com.akuhome.resource.dao.PartDao;
import com.akuhome.resource.entity.Part;
import com.akuhome.resource.enums.ResultEnum;
import com.akuhome.resource.exception.ResourceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PartService {
    @Autowired
    private PartDao partDao;
    
    public List<Part> findAllPart(){
        return partDao.findAllPart();
    }

    public Part findPartById(Integer partId){
        return partDao.findPartById(partId);
    }

    public Integer insertPart(Part part){
        int row = partDao.insertPart(part);
        if(row == 1) {
            return part.getId();
        }else{
            throw new ResourceException(ResultEnum.ARG_MISMATCH_ERROR);
        }
    }
    public Object updatePart(Part part){
        int row = partDao.updatePart(part);
        if(row == 1) {
            return null;
        }else if(row == 0){
            throw new ResourceException(ResultEnum.ARG_MISMATCH_ERROR);
        }else{
            throw new ResourceException(ResultEnum.UNKNOWN_ERROR);
        }
    }
    public Object deletePartById(Integer partId){
        int row = partDao.deletePartById(partId);
        if(row == 1){
            return null;
        }else{
            throw new ResourceException(ResultEnum.ARG_MISMATCH_ERROR);
        }
    }

    public Object addUserCount(Integer partId,Integer userCount){
        Part part = partDao.findPartById(partId);
        part.setUserCount(part.getUserCount()+userCount);
        int row = partDao.updatePart(part);
        if(row == 1){
            return part.getUserCount();
        }else{
            throw new ResourceException(ResultEnum.ARG_MISMATCH_ERROR);
        }
    }

    public Part findPartByUserId(Integer userId){
        return partDao.findPartByUserId(userId);
    }
}
